package net.larsan.dconf.util;

import static org.apache.commons.lang.Validate.notNull;

import java.util.LinkedList;

import net.larsan.dconf.DPath;

/**
 * Helper class for properties. Contains only static
 * methods at the moment.
 * 
 * @author Lars J. Nilsson
 */
public class PropertiesUtil {

	private PropertiesUtil() { }
	
	/**
	 * Given a root, create a properties key using the given path, which
	 * excludes the root. For example, using root "dom:/my"
	 * 
	 * <pre>
	 *   dom:/my/small/path = small.path
	 * </pre>
	 * 
	 * <p>If the root is null, the entire path will be returned. For 
	 * example:</p>
	 * 
	 * <pre>
	 *   dom:/my/small/path = my.small.path
	 * </pre>
	 * 
	 * @param root Root path to start key from, may be null
	 * @param path Path to use as key, must not be null
	 * @return A string properties key, never null
	 */
	public static String toPropertyKey(DPath root, DPath path) {
		notNull(path);
		if(path.equals(root)) {
			// special case, return self
			return path.getName(); // EARLY RETURN
		}
		LinkedList<String> list = new LinkedList<String>();
		DPath curr = path;
		// recurse backwards to root
		do {
			String name = curr.getName();
			if(name.length() != 0) {
				list.addFirst(curr.getName());
				curr = curr.getParent();
			} else {
				// reached the root
				break;
			}
		} while(!curr.equals(root));
		// create '.' delimited string
		StringBuilder b = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			b.append(list.get(i));
			if(i + 1 < list.size()) {
				b.append('.');
			}
		}
		return b.toString();
	}
}
